package org.tinygroup.earthworm2;

import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;

public class LogService2 {
	private final static Logger LOGGER = LoggerFactory.getLogger(LogService2.class);
	private final static LogService2 logService;
	private final static String STAGE_KEY = "earthworm_stage";
	private final static String SPAN_KEY = "earthworm_span";
	private final static String TRACE_KEY = "earthworm_trace";
	private final static String LOCAL_SPAN_KEY = "earthworm_local_span";
	static{
		LoggerFactory.putRpcVariableKey(STAGE_KEY);
		LoggerFactory.putRpcVariableKey(SPAN_KEY);
		LoggerFactory.putRpcVariableKey(TRACE_KEY);
		LoggerFactory.putRpcVariableKey(LOCAL_SPAN_KEY);
		logService = new LogService2();
	}
	public static LogService2 getInstance(){
		return logService;
	}
	public void clear(){
		LoggerFactory.removeThreadVariable(STAGE_KEY);
		LoggerFactory.removeThreadVariable(SPAN_KEY);
		LoggerFactory.removeThreadVariable(TRACE_KEY);
		LoggerFactory.removeThreadVariable(LOCAL_SPAN_KEY);
	}
	public void logStage(String stage){
		LoggerFactory.putThreadVariable(STAGE_KEY, stage);
		RpcContext2 rc = RpcContext2.get();
		if(rc!=null){
			LoggerFactory.putThreadVariable(SPAN_KEY, rc.spanId);
			LoggerFactory.putThreadVariable(TRACE_KEY, rc.traceId);
			if(rc.local!=null){
				LoggerFactory.putThreadVariable(LOCAL_SPAN_KEY, rc.local.spanId);
			}else{
				LoggerFactory.removeThreadVariable(LOCAL_SPAN_KEY);
			}
		}else{

			LoggerFactory.removeThreadVariable(SPAN_KEY);
			LoggerFactory.removeThreadVariable(TRACE_KEY);
			LoggerFactory.removeThreadVariable(TRACE_KEY);
		}
		LOGGER.logMessage(LogLevel.INFO, "stage:{}",stage);
		if(stage == "endtrace"){
			clear();
		}
	}
}
